import { Component, Input, Injector, ViewChild } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { CreateOrUpdateRoleInput, RoleEditDto, RoleServiceProxy  } from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';
import { PermissionTreeComponent } from '../components/permission-tree/permission-tree.component';

@Component({
  selector: 'roleCreateOrEditDrawer',
  templateUrl: './role-create-or-edit.component.html',
  styleUrls: ['./role-create-or-edit.component.less'],
})
export class RoleCreateOrEditComponent extends AppComponentBase {
  @Input() id?: number;

  @ViewChild('permissionTree')
  permissionTree: PermissionTreeComponent;

  roleForm: FormGroup;
  role: RoleEditDto = new RoleEditDto();

  isLoadingBtn = false;

  constructor(
    injector: Injector,
    private drawerRef: NzDrawerRef,
    private fb: FormBuilder,
    private roleService: RoleServiceProxy
  ) {
    super(injector);
  }

  ngOnInit() {
    this.roleForm = this.fb.group({
      displayName: [null, [Validators.required]],
      isDefault: [null]
    });
    //if (this.id) {
      this.roleService.getRoleForEdit(this.id)
        .subscribe(result => {
            this.role = result.role;
            console.log(result);
            this.permissionTree.editData = result;
        });
    //}
  }

  close(): void {
    this.drawerRef.close(false);
  }

  submitForm(): void {
    for (const i in this.roleForm.controls) {
      this.roleForm.controls[i].markAsDirty();
      this.roleForm.controls[i].updateValueAndValidity();
    }
    if (this.roleForm.valid) {
      this.isLoadingBtn = true;
      let model: CreateOrUpdateRoleInput = new CreateOrUpdateRoleInput();
      model.role = this.role;
      model.grantedPermissionNames = this.permissionTree.getGrantedPermissionNames();
      this.roleService.createOrUpdateRole(model)
        .subscribe(result => {
          this.isLoadingBtn = false;
          this.notify.success('操作成功！');
          this.drawerRef.close(true);
        });
    }
  }
}